package com.fa4j.third.base.proxy;

import com.fa4j.third.base.config.ThirdAdapterConfigurer;
import com.fa4j.third.base.service.ThirdConfigService;
import jakarta.validation.Validator;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.FactoryBean;

import java.lang.reflect.Proxy;
import java.util.List;

@RequiredArgsConstructor
public class ThirdProxyFactoryBean<T> implements FactoryBean<T> {

    private final Class<T> interfaceClass;
    private final ThirdConfigService thirdConfigService;
    private final List<ThirdAdapterConfigurer> configurers;
    private final Validator validator;


    @Override
    public T getObject() throws Exception {
        List<Class<T>> adapterClassList = configurers.stream()
                .flatMap(c -> c.getAdapterClassList().stream())
                .filter(interfaceClass::isAssignableFrom)
                .map(c -> (Class<T>) c)
                .toList();
        ThirdInvocationHandler<T> invocationHandler = new ThirdInvocationHandler<>(thirdConfigService, adapterClassList, validator);
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, invocationHandler);
    }

    @Override
    public Class<?> getObjectType() {
        return interfaceClass;
    }
}
